package com.sun.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.io.IOException;
import java.util.Properties;

@Configuration
@Slf4j
public class QuartzConfig implements ApplicationContextAware {

    private ApplicationContext context;

    public SchedulerFactoryBean schedulerFactoryBean(){
        SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();

        factoryBean.setSchedulerName("myScheduler");
        //用于quartz集群，启动时更新已存在得job，这样就不用每次更改targetObject后删除qrtz_job_details表对应记录了
        factoryBean.setOverwriteExistingJobs(true);
        //启动后延时10秒开始执行任务
        factoryBean.setStartupDelay(10);
        //设置spring容器上下文，用于获取容器
        factoryBean.setApplicationContext(context);

        try {
            factoryBean.setQuartzProperties(properties());
        } catch (IOException e) {
            log.error("初始化quartz配置文件错误,错误原因",e);
            e.printStackTrace();
        }

//        factoryBean.setApplicationContextSchedulerContextKey();
        return factoryBean;
    }

    private Properties properties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        //设置quartz配置文件位置
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        //正式读取配置文件
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

}
